package com.umer.pinban.user;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.core.content.FileProvider;
import com.afollestad.materialdialogs.MaterialDialog;
import com.common.base.activity.BaseActivity;
import com.common.bean.InfoResult;
import com.common.bean.MsgBean;
import com.common.bean.UserInfo;
import com.common.okhttp.OkSimpleRequest;
import com.common.utils.AntiShake;
import com.common.utils.Constants;
import com.common.utils.EventConstants;
import com.common.utils.GlideUtils;
import com.common.utils.file.FileUtils;
import com.umer.pinban.AppHolder;
import com.umer.pinban.R;
import com.umer.pinban.utils.CountDownTimer;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;
import java.io.File;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * 修改信息
 */

public class UpDateUserActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.linear_code)
    LinearLayout linearCode;
    @BindView(R.id.tv_name)
    EditText tvName;
    @BindView(R.id.tv_address)
    EditText tvAddress;
    @BindView(R.id.iv)
    ImageView iv;
    @BindView(R.id.btn)
    Button btn;
    private UserInfo userInfo;
    CountDownTimer timer1 = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            tvCode.setText(millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            tvCode.setText("重新获取验证码");
        }
    };

    @Override
    public View isSupportLoadSirEnabled() {
        return null;
    }

    @Override
    public boolean isImmersionBarEnabled() {
        return false;
    }

    @Override
    public boolean isSupportSwipeBackEnabled() {
        return false;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_update_user;
    }

    @Override
    public void init() {
        userInfo = AppHolder.getInstance().getUserInfo();
        if(userInfo!=null){
            tvPhone.setText(""+ userInfo.getPhone());
            tvName.setText(userInfo.getName());
            tvAddress.setText(userInfo.getAddress());
            GlideUtils.getInstance().loadAddPic(this,
                    Constants.IP_PORT_DEFAULT_PICTURE + userInfo.getHeader(), iv);
        }
    }

    @Override
    public void loadData() {

    }

    @OnClick({R.id.linear_back, R.id.iv,R.id.btn,R.id.tv_code})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                if (AntiShake.check(view.getId())) {
                    return;
                }
                finish();
                break;
            //提交按钮
            case R.id.btn:
                if(TextUtils.isEmpty(etCode.getText().toString())){
                    showToast("请输入验证码");
                }else if(TextUtils.isEmpty(tvName.getText().toString())){
                    showToast("请输入店铺名称");
                }else if(TextUtils.isEmpty(tvAddress.getText().toString())){
                    showToast("请输入店铺地址");
                }else {
                    updateUserInfo();
                }
                break;
            case R.id.tv_code:
                if(TextUtils.isEmpty(tvPhone.getText().toString().trim())){
                    showToast("请输入手机号码");
                }else {
                    timer1.start();
                    OkSimpleRequest request = new OkSimpleRequest<>(R.id.authPhone,
                            Constants.authPhone);
                    request.addParams("phone", tvPhone.getText().toString().trim());
                    request.addParams("type", "updateShop");
                    requestOkhttpSimple(request);
                }
                break;
            case R.id.iv:
                if (AntiShake.check(view.getId())) {
                    return;
                }
                PermissionGen.needPermission(this, 100,
                        new String[]{
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA
                        });
                break;
            default:
                break;
        }
    }

    @PermissionSuccess(requestCode = 100)
    public void doSomething() {
        new MaterialDialog.Builder(this)
                .title("选择来源")
                .items(R.array.photo_resouce)
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View view,
                                            int which, CharSequence text) {
                        switch (which) {
                            case 0:
                                camera();
                                break;
                            case 1:
                                selectImg();
                                break;
                            default:
                                break;
                        }
                    }
                })
                .backgroundColor(getColor(R.color.white))
                .itemsColor(getColor(R.color.black))
                .negativeColor(getColor(R.color.colorPrimary))
                .positiveColor(getColor(R.color.colorPrimary))
                .titleColor(getColor(R.color.black))
                .show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //相册返回
        if (requestCode == RESULT_CODE_2) {

            /**
             * 第三方相册选择
             */
            if (mUris != null && mUris.size() > 0) {
                mUris.clear();
            }
            mUris = Matisse.obtainResult(data);
            if (mUris != null && mUris.size() > 0) {
                File file = new File(getRealFilePath(mUris.get(0)));
                Uri uri = Uri.fromFile(file);
                cropRawPhoto(uri);
            }
        }
        //相机返回
        else if (requestCode == RESULT_CODE_1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // 调用裁剪方法
                cropRawPhoto(mProviderUri);
            } else {
                cropRawPhoto(mUri);
            }
        } else if (requestCode == UCrop.REQUEST_CROP) {
            if (data != null) {
                Uri croppedFileUri = UCrop.getOutput(data);
                if (croppedFileUri != null) {
                    pathCrop = getRealFilePath(croppedFileUri);
                    File file = new File(pathCrop);
                    GlideUtils.getInstance().showNativeFile(this,file,iv);
                }
            }

        } else if (requestCode == UCrop.RESULT_ERROR) {
            if (data != null) {
                showToast(UCrop.getError(data) + "");
            }
            pathCrop = "";
        }
    }

    @Override
    protected void onSuccess(int what, InfoResult t) {
        switch (what){
            case R.id.updateShopInfo:
                hideProgress();
                showToast(t.getDesc());
                MsgBean msgBean = new MsgBean();
                msgBean.setFlag(EventConstants.update_user_sucess);
                getEventBus().post(msgBean);
                finish();
                break;
            case R.id.authPhone:
                showToast(t.getDesc());
                break;
            default:break;
        }
    }

    @Override
    protected void onFail(int what, InfoResult t) {
        switch (what){
            case R.id.updateShopInfo:
                hideProgress();
                showToast(t.getDesc());
                break;
            case R.id.authPhone:
                showToast(t.getDesc());
                break;
            default:break;
        }
    }

    // 没有截取时的图片路径
    private String pathPhoto = "";
    //截取后的图片路径
    private String pathCrop = "";
    // 7.0 以上的uri
    private Uri mProviderUri;
    // 7.0 以下的uri
    private Uri mUri;
    public static final int RESULT_CODE_1 = 201;

    /**
     * 拍照
     * index 1老板头像 2店铺图像
     */
    private void camera() {
        File file = null;
        FileUtils.getInstance().createPhotoDirectory();
        file = new File(Constants.DEFAULT_PHOTO_IMAGE_DIR, System.currentTimeMillis() + ".png");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Android7.0以上URI
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //通过FileProvider创建一个content类型的Uri
            mProviderUri = FileProvider.getUriForFile(this, "com.umer.pinban.fileprovider", file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mProviderUri);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {

            mUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        }
        try {
            startActivityForResult(intent, RESULT_CODE_1);

        } catch (ActivityNotFoundException anf) {
            showToast("摄像头未准备好!");
        }
    }


    /**
     * 相册
     */
    public static final int RESULT_CODE_2 = 202;
    private int flag = 2;//蓝色主题(知乎主题) 2 Dracula主题
    private List<Uri> mUris;//相册选择的图片uri

    private void selectImg() {
        FileUtils.getInstance().createPhotoDirectory();
        //调用系统相册
        /*Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, RESULT_CODE_2);*/
        Matisse.from(this)
                .choose(MimeType.of(MimeType.JPEG, MimeType.PNG))
                .theme(R.style.Matisse_Dracula)
                .countable(false)
                .maxSelectable(1)
                .imageEngine(new PicassoEngine())
                .forResult(RESULT_CODE_2);
    }

    /**
     * 截取图片
     */
    private void cropRawPhoto(Uri uri) {
        // 修改配置参数（我这里只是列出了部分配置，并不是全部）
        UCrop.Options options = new UCrop.Options();
        options.setToolbarColor(getColor(R.color.colorPrimary));
        options.setStatusBarColor(getColor(R.color.colorPrimary));
        /*options.setToolbarColor(getThemeHelper().getPrimaryColor());
        options.setStatusBarColor(getThemeHelper().getPrimaryColor());*/
      /*  options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        // 是否隐藏底部工具
        options.setHideBottomControls(false);
        // 图片格式
        options.setCompressionFormat(Bitmap.CompressFormat.PNG);
        // 设置图片压缩质量
        options.setCompressionQuality(100);
        // 是否让用户调整范围(默认false)，如果开启，可能会造成剪切的图片的长宽比不是设定的
        // 如果不开启，用户不能拖动选框，只能缩放图片
        //options.setFreeStyleCropEnabled(true);*/
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //是否能调整裁剪框
        options.setFreeStyleCropEnabled(true);

        // 设置源uri及目标uri
        UCrop.of(uri, Uri.fromFile(new File(Constants.DEFAULT_PHOTO_IMAGE_DIR, System.currentTimeMillis() + ".png")))
                .withAspectRatio(1, 1)
                .withMaxResultSize(200, 200)
                .withOptions(options)
                .start(UpDateUserActivity.this);
    }

    /**
     * uri转path
     */
    private String getRealFilePath(final Uri uri) {
        if (null == uri) {
            return null;
        }
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    private void updateUserInfo() {
        showProgress("正在提交,请稍后...");
        OkSimpleRequest<InfoResult> request = new OkSimpleRequest<>(R.id.updateShopInfo,
                Constants.updateShopInfo);
        request.addParams("authCode", etCode.getText().toString());
        request.addParams("phone", userInfo.getPhone());
        request.addParams("shopId", userInfo.getShopId());
        request.addParams("name", tvName.getText().toString());
        request.addParams("address", tvAddress.getText().toString());
        if(!TextUtils.isEmpty(pathCrop)){
            request.addParams("files", new File(pathCrop));
            request.setFile(true);
        }
        request.setHeader(true);
        requestOkhttpSimple(request);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer1!=null){
            timer1.cancel();
        }
    }
}
